package com.dragon.exception;

import com.dragon.pojo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
    @ExceptionHandler(DataIntegrityViolationException.class)
    public Result handleDataIntegrityViolationException(DataIntegrityViolationException e){
        String message = e.getMostSpecificCause().getMessage();
        log.warn("发生数据完整性约束冲突:{}",message);
        if(message.contains("user.unique")){
            return Result.error("用户名已存在，请重新输入",409);
        }
        if(message.contains("problem.problem_unique")){
            return Result.error("题目名已存在",409);
        }
        if(message.contains("training.training_unique")){
            return Result.error("题单名已存在",409);
        }
        if(message.contains("contest.contest_unique")){
            return Result.error("比赛名已存在",409);
        }
        return Result.error("操作失败，请重新输入");
    }
    @ExceptionHandler(NoResourceFoundException.class)
//    @ResponseStatus(HttpStatus.NOT_FOUND) // 返回 HTTP 404 状态码
    public Result handleNoResourceFoundException(NoResourceFoundException e){
        log.warn("请求的静态资源不存在: {}", e.getResourcePath());
        return Result.error("请求的资源不存在");
    }

    @ExceptionHandler(Exception.class)
    public Result handleException(Exception e) {
        String message = e.getMessage();
        if(message.contains("JWT expired")) {
            return Result.error("登录已过期",401);
        } else if (message.contains("Malformed protected header JSON: Unable to deserialize") || message.contains("JWT signature does not match locally computed signature.")) {
            return Result.error("登录令牌无效",401);
        }
//        throw new RuntimeException(e);
        log.error("服务器发生运行错误",e);
        return Result.error("系统繁忙，请稍后再试");
    }
}
